package com.ruirenyun.util.annotation.page;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.page.PageMethod;
import com.ruirenyun.entity.base.req.PageSearchVo;
import com.ruirenyun.entity.base.resp.PageRespVo;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * @author Deng Ye
 * @version 1.0
 * @date 2020/9/29
 * @description 分页参数设置AOP
 * @modifiedBy
 */
@Aspect
@Component
public class PageQueryAop {

    @Around("@annotation(pagingQuery)")
    public Object pagingQuery(ProceedingJoinPoint joinPoint, PageQuery pagingQuery) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> returnType = signature.getMethod().getReturnType();
        if (returnType == PageRespVo.class) {
            String pageNumParameterName = pagingQuery.pageNumParameterName();
            String pageSizeParameterName = pagingQuery.pageSizeParameterName();
            //获取request，从中获取分页参数
            Object[] args = joinPoint.getArgs();
            String pageNum = null;
            String pageSize = null;
            for (Object arg : args) {
                if (arg instanceof PageSearchVo) {
                    pageNum = ((PageSearchVo<?>) arg).getPageNum();
                    pageSize = ((PageSearchVo<?>) arg).getPageSize();
                    break;
                }
                Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(arg));
                Object num = map.get(pageNumParameterName);
                Object size = map.get(pageSizeParameterName);
                if (Objects.nonNull(num) && Objects.nonNull(size)) {
                    pageNum = num.toString();
                    pageSize = size.toString();
                    break;
                }
            }
            if (StringUtils.isNotBlank(pageNum) && StringUtils.isNotBlank(pageSize)) {
                try {
                    PageMethod.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
                    return joinPoint.proceed();
                } finally {
                    //保证线程变量被清除
                    if (PageMethod.getLocalPage() != null) {
                        PageMethod.clearPage();
                    }
                }
            } else {
                try {
                    PageMethod.startPage(1, 10);
                    return joinPoint.proceed();
                } finally {
                    //保证线程变量被清除
                    if (PageMethod.getLocalPage() != null) {
                        PageMethod.clearPage();
                    }
                }
            }
        }
        return joinPoint.proceed();
    }
}
